<script setup>
import { User, Lock, MessageBox } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {useRouter} from 'vue-router'
import {useTokenStore} from '@/stores/token.js'
import {userRegisterService,userLoginService,authService,editService,sendService,loginByCapService} from '@/api/user.js'
const router = useRouter();
const tokenStore = useTokenStore();

const activeName = ref('first');

const handleClick = (tab, event) => {
console.log(tab, event);
}


//注册页显示标志量
const isRegister = ref(false);

//用户注册表单数据模型
const registerFormData = ref({
  username:'',
  password:'',
  repassword:'',
  phoneNumber:'',
  captcha:''
})

//用户注册表单数据模型
const registerData = ref({
  username:'',
  password:'',
  phoneNumber:'',
  role:0,
  param:''
})

//用户登录数据模型
const loginData = ref({
  phoneNumber:'',
  password:''
})

//验证码登录数据模型
const capData = ref({
  phoneNumber:'',
  param:''
})

//用户

//清空模型
const clearRegisterFormData = ()=>{
  registerFormData.value.username='',
  registerFormData.value.password='',
  registerFormData.value.repassword='',
  registerFormData.value.phoneNumber='',
  registerFormData.value.captcha=''
}

const clearRegisterData = ()=>{
  registerData.value.username='',
  registerData.value.password='',
  registerData.value.role=0,
  registerData.value.phoneNumber='',
  registerData.value.param=''
}



//密码校验
const checkRePassword = (rules,value,callback)=>{
    if(value ===''){
        callback(new Error('再次确认密码'))
    }else if(value!==registerFormData.value.password){
        callback(new Error('确保两次输入密码一致'))
    }else{
        callback()
    }
    
}


//表单校验规则
const rules = ref({
  username:[{
    required:true,message:'用户名不能为空',trigger:'change'
    },
    {
      min:2,max:18,message:'用户名长度应在2到18',trigger:'change'
    }
  ],
  password:[{
    required:true,message:'密码不能为空',trigger:'change'
  },{
    min:3,max:18,message:'密码长度应在3-18个字符之间',trigger:'change'
  }],
  repassword:[{validator:checkRePassword,trigger:'change'}],
  phoneNumber:[{
    required:true,
      message:'手机号不能为空',
      trigger:'change'
    },
    {
      min:11,max:11,message:'手机号不正确',trigger:'change'
    }],
  captcha:[{
    required:true,
      message:'验证码不能为空',
      trigger:'change'
    },
    {
      min:4,max:6,message:'验证码长度不正确',trigger:'change'
    }]

})


//倒计时函数
const countDownTime = ref(60)
const isCountDown = ref(false)
const startTimer=()=> {
  if(!isCountDown.value){
    isCountDown.value = true;
    const timer = setInterval(()=>{
      if(countDownTime.value>0){
        countDownTime.value--;
      }else{
        clearInterval(timer);
        isCountDown.value = false;
        countDownTime.value = 60;
      }
    },1000);
  }

      
        
}

const register =async()=>{
  registerData.value.username = registerFormData.value.username;
  registerData.value.password = registerFormData.value.password;
  registerData.value.param = registerFormData.value.captcha;
  registerData.value.phoneNumber = registerFormData.value.phoneNumber;
  console.log(registerData.value);
  let result = await userRegisterService(registerData.value);
  await ElMessage.success('注册成功，请登录');
  isRegister.value = false;
  
}


import { usePhoneStore } from '@/stores/phone.js'

const phoneStore = usePhoneStore();

//密码登录
const login = async()=>{
    let r = await userLoginService(loginData.value);
    phoneStore.setPhone(loginData.value.phoneNumber);
    console.log(r.data.desc);
    ElMessage.success('登录成功');
    tokenStore.setToken(r.data.desc);
    console.log("登录成功后看有没有"+tokenStore.token);
    router.push('/');
}

//验证码登录
const loginByCap = async()=>{
    console.log(capData.value);
    let r = await loginByCapService(capData.value);
    phoneStore.setPhone(capData.value.phoneNumber);

    console.log("日志输出：  ",r.data);
    ElMessage.success('登录成功');
    tokenStore.setToken(r.data.desc);
    console.log("登录成功后看有没有"+tokenStore.token);
    router.push('/');
}

//发送验证码
const send = async () => {
  startTimer();
  try {
    let result = await sendService(capData.value.phoneNumber);
    console.log(result.data);
    ElMessage.success('验证码发送成功');
  } catch (error) {
    console.error('发送验证码失败:', error);
    ElMessage.error('验证码发送失败');
  }
};

</script>

<template>
  <div class="all">
    <el-row class="login-page">
        <el-col :span="12" class="bg"></el-col>
        <el-col :span="6" :offset="3" class="form">
            <!-- 注册表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerFormData" :rules="rules">
                <el-form-item>
                    <h1>注册</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerFormData.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerFormData.password"></el-input>
                </el-form-item>
                <el-form-item prop="repassword">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerFormData.repassword"></el-input>
                </el-form-item>
                <el-form-item prop="phoneNumber">
                    <el-input  type="" placeholder="请输入手机号" v-model="registerFormData.phoneNumber"></el-input>
                </el-form-item>
                <el-form-item prop="captcha">
                    <el-input type="captcha" placeholder="请输入验证码" v-model="registerFormData.captcha"></el-input>
                    <button type="button" id="countdownButton" class="countdown-button" @click="send">{{isCountDown?`${countDownTime}秒后重送`:'发送验证码'}}</button>
                </el-form-item>
                <!-- 注册按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="register" :plain="true">
                        注册
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterFormData();">
                        ← 返回
                    </el-link>
                </el-form-item>
            </el-form>
            <!-- 登录表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-else :rules="rules" :model="loginData">
                <el-form-item>
                    <h1>用户登录</h1>
                </el-form-item>


                <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="密码登录" name="first">
                  <el-form-item prop="phoneNumber">
                    <el-input :prefix-icon="User" placeholder="请输入手机号" v-model="loginData.phoneNumber"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="loginData.password"></el-input>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        <el-checkbox>记住我</el-checkbox>
                        <el-link type="primary" :underline="false">忘记密码？</el-link>
                    </div>
                </el-form-item>
                <!-- 登录按钮 -->

                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
                </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="验证码登录" name="second">
                  <el-form-item prop="phoneNumber">
                    <el-input :prefix-icon="User" placeholder="请输入手机号" v-model="capData.phoneNumber"></el-input>
                </el-form-item>
                <el-form-item prop="captcha" style="display: flex;">
                    <el-input type="captcha" placeholder="请输入验证码" v-model="capData.param" style="width: 70%;"></el-input>


                    <el-button class="button" type="primary" style="width: 30%;margin-left:0px;" @click="send">{{isCountDown?`${countDownTime}秒后重送`:'发送验证码'}}</el-button>
                </el-form-item>

                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="loginByCap">登录</el-button>
                </el-form-item>
                </el-tab-pane>
<!--                <el-tab-pane label="扫码登录" name="third">-->
<!--                  <img src="@/assets/img/QRcode.png">-->
<!--                  <span>扫码给哥们爆金币</span>-->
<!--                </el-tab-pane>-->
              </el-tabs>

                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = true;clearLoginData">
                        注册 →
                    </el-link>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>

/*倒计时 */
.countdown-button {
            font-size: 14px;
            cursor: pointer;
            background-color:#a8a6a6;
            position: absolute;
            top:0%;
            left: 100%;
            float: left;
            width: 80px;
            height: 40px;

            transition: background-color 0.3s, border 0.3s;
        }


.countdown-button:hover {
    background-color: #e0e0e0;
    border-color: #bbb;
}

/**tabs */
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.all{
  background-image: url('@/assets/img/login_img.png'); /* 替换为你的图片路径 */
  background-size: cover; /* 背景图片覆盖整个元素 */
   background-position: center; /* 背景图片居中显示 */
  background-repeat: no-repeat; /* 背景图片不重复 */
  height: auto; /* 元素的高度，根据需要调整 */
  width: 100%;
}

/* 样式 */
.login-page {
    height: 100vh;
    width: 100vw;
    background-color: #fff;

    .bg{
      background: url('@/assets/img/login_img.png') no-repeat 60% center / 100% auto;
      background-color:#f1e1d2;
      border-radius: 0 20px 20px 0;
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
  }
</style>